﻿{%              if GenerateNullableReferenceTypes -%}
private string ConvertToString(object? value, System.Globalization.CultureInfo cultureInfo)
{%              else -%}
private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo)
{%              endif -%}
{
    if (value == null)
    {
        return "";
    }

    if (value is System.Enum)
    {
        var name = System.Enum.GetName(value.GetType(), value);
        if (name != null)
        {
            var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name);
            if (field != null)
            {
                var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) 
                    as System.Runtime.Serialization.EnumMemberAttribute;
                if (attribute != null)
                {
                    return attribute.Value != null ? attribute.Value : name;
                }
            }

            var converted = System.Convert.ToString(System.Convert.ChangeType(value, System.Enum.GetUnderlyingType(value.GetType()), cultureInfo));
            return converted == null ? string.Empty : converted;
        }
    }
    else if (value is bool) 
    {
        return System.Convert.ToString((bool)value, cultureInfo).ToLowerInvariant();
    }
    else if (value is byte[])
    {
        return System.Convert.ToBase64String((byte[]) value);
    }
    else if (value is string[])
    {
        return string.Join(",", (string[])value);
    }
    else if (value.GetType().IsArray)
    {
        var valueArray = (System.Array)value;
        var valueTextArray = new string[valueArray.Length];
        for (var i = 0; i < valueArray.Length; i++)
        {
            valueTextArray[i] = ConvertToString(valueArray.GetValue(i), cultureInfo);
        }
        return string.Join(",", valueTextArray);
    }

    var result = System.Convert.ToString(value, cultureInfo);
    return result == null ? "" : result;
}
